package at.guigu.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

// 分配置文件对应的类不用配置@Configuration以及@ComponentScan注解
// 加载properties配置文件<context:property-placeholder location="classpath:jdbc.properties"/>
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfiguration {
    @Value("${jdbc.driverClassName}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    /**
     * Druid对应的bean
     * Spring会将当前方法的返回值以指定的id存储到Spring的IOC容器中
     * @return
     * @throws Exception
     */
    @Bean("dataSourceDruid")
    public DataSource getDruidDataSource() throws Exception{
        // 创建数据源对象
        DruidDataSource dataSource = new DruidDataSource();
        // 设置数据源基本连接数据
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    // 事务管理器配置
    @Bean
    public PlatformTransactionManager transactionManager(@Qualifier("dataSourceDruid") DataSource dataSource) {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }
}
